package cn.bone.sentinel.web;

import cn.bone.sentinel.bean.CommonResult;
import cn.bone.sentinel.bean.Person;
import cn.bone.sentinel.bean.Ref;
import cn.bone.sentinel.service.IDemoService;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/demo2")
public class SentinelController {

    @Resource
    private IDemoService demoService;

    private boolean temp = true;

    @RequestMapping("/test01")
    public CommonResult test01(){


        List<FlowRule> rules = FlowRuleManager.getRules();
        for(FlowRule rule : rules){
            System.out.println(JSON.toJSONString(rule));
        }

        CommonResult<?> result = null;

        temp = true;

        Random random = new Random();
        while (temp) {

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Entry entry = null;
            try {
                entry = SphU.entry("person-01");
                result = demoService.hello(new Person());
            } catch (BlockException e) {
                System.out.println("block!!");
                e.printStackTrace();
                result = Ref.error("请求太多啦");
            } finally {
                if (entry != null) {
                    entry.exit();
                }
            }
        }
        return result;
    }

    @PostConstruct
    private void initFlowRules(){
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule = new FlowRule();
        rule.setResource("person-01");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(10);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    @RequestMapping("/test02")
    public String test02(){
        List<FlowRule> rules = FlowRuleManager.getRules();
        for(FlowRule rule : rules){
            if(rule.getResource().equals("person-01")){
                rule.setCount(10);
                System.out.println("修改person-01的规则");
            }
        }
        FlowRuleManager.loadRules(rules);
        temp = false;
        return "ok";
    }
}
